/**   
 * @Title: SDCardFileExplorerActivity.java 
 * @Package: com.rename.icode.activity 
 * @Description: Administrator版权所有
 * @author Administrator  
 * @date 2015-4-15 下午3:21:29 
 * @version  
 */

package com.rename.icode.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.rename.icode.R;
import com.rename.icode.comm.Constants;
import com.rename.icode.model.CodeFile;
import com.rename.icode.utils.FileUtil;
import com.rename.icode.utils.LogUtil;
import com.rename.icode.view.SDCardFilesAdapter;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description 实现了...功能
 * @author Administrator
 * @date 2015-4-15 下午3:21:29
 * @version V1.0
 */

public class SDCardFileExplorerActivity extends ActivitySupport {
	
	private static final String TAG = "SDCardFileExplorerActivity";

	@SuppressLint("SdCardPath")
	private static final String ROOT = "/mnt/sdcard/";
	public static final String SD_FILE_KEY = "sd_file_key";

	private TextView tvPath; // 当前路径
	private ListView lvFiles; // 文件列表
	private Button backBtn; // 返回上一级目录
	private Button selectBtn; // 确定选择按钮
	private Button calcelBtn; // 取消选择按钮

	private SDCardFilesAdapter adapter;
	private File selectedFile; // 选中的文件

	// 记录当前的父文件夹
	private File currentParent;

	// 记录当前路径下的所有文件夹的文件数组
	private File[] currentFiles;
	
	private static final int BACK_TO_MAIN = 0; 
	private Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case BACK_TO_MAIN:
				setResult(Activity.RESULT_OK);
				break;

			default:
				break;
			}
		}
		
	};

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_sdcard_explorer);

		// 获取系统的SDCard的目录
		File root = new File(ROOT);
		if (root.exists()) { // 如果SD卡存在的话
			currentParent = root;
			currentFiles = root.listFiles();
		} else {
			showToast("SDCard为正确挂载");
			return;
		}

		init();
	}

	private void init() {
		getICodeApplication().addActivity(this);

		tvPath = (TextView) this.findViewById(R.id.tvpath);

		adapter = new SDCardFilesAdapter(context, currentFiles);

		lvFiles = (ListView) this.findViewById(R.id.files);
		lvFiles.setAdapter(adapter);
		lvFiles.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapterView, View view,
					int position, long id) {

				TextView text = (TextView) view.findViewById(R.id.file_name);
				File file = (File) view.findViewById(R.id.file_name).getTag();
				// 如果用户单击了文件，直接返回，不做任何处理
				if (file.isFile()) {
					selectedFile = file;
					// TODO 文件名颜色变红，选择按钮恢复焦点
					updateSelectedStatus(true);
					adapter.updateSelection(position, true);
				} else {
					updateSelectedStatus(false);
					adapter.updateSelection(position, false);
					// 获取用户点击的文件夹 下的所有文件
					File[] tem = file.listFiles();
					if (tem == null || tem.length == 0) {
						showToast("当前路径不可访问或者该路径下没有文件");
					} else {
						// 获取用户单击的列表项对应的文件夹，设为当前的父文件夹
						currentParent = file;
						// 保存当前的父文件夹内的全部文件和文件夹
						currentFiles = tem;
					}
				}

				// 再次更新ListView
				refreshListView();
			}
		});

		backBtn = (Button) this.findViewById(R.id.back_btn);
		// 获取上一级目录
		backBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				try {

					if (!currentParent.getCanonicalPath().equals("/mnt/sdcard")) {

						// 获取上一级目录
						currentParent = currentParent.getParentFile();
						// 列出当前目录下的所有文件
						currentFiles = currentParent.listFiles();
						//
						updateSelectedStatus(false);
						adapter.updateSelection(false);
						// 再次更新ListView
						refreshListView();
					}
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}

			}
		});

		selectBtn = (Button) findViewById(R.id.select_btn);
		selectBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				CodeFile codeFile = new CodeFile();
				codeFile.setId("");
				codeFile.setName(selectedFile.getName());
				codeFile.setDetail("");
				codeFile.setPath(Constants.CODE_LOCAL_DIR + selectedFile.getName());
				if (selectedFile.getName().endsWith(Constants.SUFFIX_C)) {
					codeFile.setType(Constants.TYPE_C);
				} else if (selectedFile.getName().endsWith(Constants.SUFFIX_CPP)) {
					codeFile.setType(Constants.TYPE_CPP);
				} else if (selectedFile.getName().endsWith(Constants.SUFFIX_JAVA)) {
					codeFile.setType(Constants.TYPE_JAVA);
				} else {
					showToast("此文件格式不支持");
				}
				LogUtil.i(TAG, "codefile is " + codeFile.toString());
				Intent intent = new Intent();
				Bundle bundle = new Bundle();
				bundle.putParcelable(SD_FILE_KEY, codeFile);
				intent.putExtras(bundle);
				setResult(Activity.RESULT_OK, intent);
				finish();
				
			}
		});
		updateSelectedStatus(false);

		calcelBtn = (Button) findViewById(R.id.cancel_btn);
		calcelBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});

	}

	private void refreshListView() {
		adapter.refreshList(currentFiles);
		try {
			tvPath.setText("当前路径为:" + currentParent.getCanonicalPath());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void updateSelectedStatus(boolean selected) {
		if (selected) {
			selectBtn.setAlpha(1.0f);
			selectBtn.setClickable(true);
		} else {
			selectBtn.setAlpha(0.7f);
			selectBtn.setClickable(false);
		}
	}

	@Override
	protected void onResume() {
		refreshListView();
		super.onResume();
	}

}
